# coding=utf-8
import time
import os,sys
import math
BASE_PATH = os.path.dirname(
    os.path.dirname(os.path.abspath(__file__))
)
sys.path.insert(0,BASE_PATH)

from bin import get_Webdriver
from .public import Public

class TaskManage_Action:
    def __init__(self):
        self.driver = get_Webdriver.Get_Webdriver().driver

    def jumpToTaskManage(self):
        """跳转到任务管理界面"""
        curl = Public().getCurrentUrl()
        if 'task/main.html' not in curl:
            self.driver.click("link_text=>任务管理")
        else:
            self.driver.F5()

    def clicktopfolderByid(self, folderid='treeDemo_1'):
        """根据顶级文件夹id点击文件夹，treeDemo_1为默认文件夹"""
        self.driver.click('css=>#{}_span'.format(folderid))

    def clicktopfolderMoreByid(self, folderid='treeDemo_1'):
        """根据顶级文件夹id点击文件夹后more，treeDemo_1为默认文件夹"""
        self.driver.click('css=>#addBtn_{}'.format(folderid))

    def folderclickDel(self):
        """点击删除文件夹"""
        self.driver.click('css=>td[data-num="2"]')

    def getAllTopfolderList(self):
        """获取所有顶级文件夹的id"""
        folder_list = self.driver.get_attributes('css=>li[class="level0"]', 'id')
        return folder_list

    def getFnameByid(self, fid):
        """根据id获取文件夹名称"""
        fname = self.driver.get_text('css=>#{}_span'.format(fid))
        return fname

    def inputFoldername(self, fname):
        """输入文件夹的名称"""
        self.driver.clear('css=>#name')
        self.driver.type('css=>#name', fname)

    def clickAddSubmit(self):
        """输入文件夹名称时点击确定按钮"""
        self.driver.click('css=>#submit')

    def clickUploadSubmit(self):
        """上传文件时点击确定按钮"""
        self.driver.click('css=>#ctlBtn')

    def clickUploadSecretarySubmit(self):
        """上传文件时点击确定按钮"""
        self.driver.click('css=>#save')

    def clickAddCancle(self):
        """输入文件夹名称时点击取消按钮"""
        self.driver.click('css=>button[onclick="closeDlg()"]')


    def addFolder(self, foldername, topfolderid='treeDemo_1', location='same', clicksubmit='y'):
        """点击一个文件夹后的...按钮，添加文件夹，
        foldername：文件名
        topfolderid:源文件夹id
        location:同级或下级
        """
        self.clicktopfolderByid(topfolderid)
        time.sleep(0.2)
        self.clicktopfolderMoreByid(topfolderid)
        time.sleep(0.2)
        if location == 'same':
            timestap = self.folderclickAddSame()
            time.sleep(0.2)
            self.driver.switch_to_frame('name=>{}'.format(timestap))
        elif location == 'lower':
            timestap = self.folderclickAddLower()
            time.sleep(0.2)
            self.driver.switch_to_frame('name=>{}'.format(timestap))
        self.inputFoldername(foldername)
        time.sleep(0.2)
        if clicksubmit == 'y':
            self.clickAddSubmit()
        elif clicksubmit == 'n':
            self.clickAddCancle()

    def renameFolder(self, foldername, topfolderid, clicksubmit='y'):
        """点击一个文件夹后的...按钮选择重命名，
        foldername：文件名
        topfolderid:源文件夹id
        """
        self.clicktopfolderByid(topfolderid)
        time.sleep(0.2)
        self.clicktopfolderMoreByid(topfolderid)
        time.sleep(0.2)
        timestap = self.folderclickRename()
        time.sleep(0.2)
        self.driver.switch_to_frame('name=>{}'.format(timestap))
        self.inputFoldername(foldername)
        time.sleep(0.2)
        if clicksubmit == 'y':
            self.clickAddSubmit()
        elif clicksubmit == 'n':
            self.clickAddCancle()

    def returntoDefaultframe(self):
        self.driver.switch_to_frame_out()

    def mouseMoveOnClick(self, element):
        """
        鼠标悬停事件出现菜单,并点击
        element要点击的元素位置
        """
        script = '$(arguments[0]).click()'
        self.driver.js(script, element)

    def getSonfolderIds(self, fatherid='treeDemo_1'):
        """通过父文件夹id查询所有子文件id"""
        self.driver.click('css=>#{}_switch'.format(fatherid))
        sonfolderIds = self.driver.get_attributes(
            'css=>#{}_ul>li>a>span[style="background:url(../style/icon/class.png) 0 0 no-repeat;"]'.format(fatherid),
            'id')
        return sonfolderIds

    def getSonfileIds(self, fatherid='treeDemo_1'):
        """通过父文件夹id查询所有子文id"""
        self.driver.click('css=>#{}_switch'.format(fatherid))
        sonfileIds = self.driver.get_attributes(
            'css=>#{}_ul>li>a>span[style="background:url(../style/icon/schema.png) 0 0 no-repeat;"]'.format(fatherid),
            'id')
        return sonfileIds

    def folderclickAddSame(self):
        """点击添加同级文件夹，并返时间戳"""
        self.driver.click('css=>td[data-num="0"]')
        time.sleep(0.5)
        labelledby = self.driver.get_attribute(
            'css=>div[class="ui-popup ui-popup-modal ui-popup-show ui-popup-focus"]', 'aria-labelledby')
        timestap = labelledby.split(':')[1]
        return timestap

    def folderclickAddLower(self):
        """点击添加下级文件夹，并返时间戳"""
        self.driver.click('css=>td[data-num="1"]')
        time.sleep(0.5)
        labelledby = self.driver.get_attribute(
            'css=>div[class="ui-popup ui-popup-modal ui-popup-show ui-popup-focus"]', 'aria-labelledby')
        timestap = labelledby.split(':')[1]
        return timestap

    def folderclickRename(self):
        """点击重命名文件夹，并返时间戳"""
        self.driver.click('css=>td[data-num="3"]')
        time.sleep(0.5)
        labelledby = self.driver.get_attribute(
            'css=>div[class="ui-popup ui-popup-modal ui-popup-show ui-popup-focus"]', 'aria-labelledby')
        timestap = labelledby.split(':')[1]
        return timestap

    def clickAddTask(self):
        """点击添加任务按钮"""
        self.driver.click("css=>a[href='/task/taskeditor.html']")

    def getAllSearchQueryId(self):
        """获取所有操作记录id"""
        query_list = self.driver.get_attributes('css=>#searchList>option', 'value')
        return query_list

    def getAllSearchOperateId(self):
        """获取所有操作记录id"""
        query_list = self.driver.get_attributes('css=>#operateList>option', 'value')
        return query_list

    def chooseSearchQuery(self, locate=1):
        """选择查询条件,默认选择第一个非空的,locate=0选择无"""
        querylist = self.getAllSearchQueryId()
        self.driver.select_value("css=>#searchList", querylist[locate])

    def chooseSearchOperate(self, locate=1):
        """选择操作记录,默认选择第一个非空的,locate=0选择无"""
        operatelist = self.getAllSearchOperateId()
        self.driver.select_value("css=>#operateList", operatelist[locate])

    def getAllTaskFileid(self):
        """获取所有第一级任务文件夹id"""
        query_list = self.driver.get_attributes('css=>#taskFolderTree>li', 'id')
        return query_list

    def getAllSonTaskFileid(self, Ftid):
        """获取指定任务文件夹下的所有子文件夹id"""
        query_list = self.driver.get_attributes('css=>#{}>ul>li'.format(Ftid), 'id')
        return query_list

    def clickTaskFileSwitch(self, Fid):
        """根据父文件夹id，点击父文件夹前的+号"""
        self.driver.click("css=>#{}_switch".format(Fid))

    def choseTaskFileByid(self, Fid):
        """根据id选择文件夹"""
        self.driver.click("css=>#{}_check".format(Fid))

    def typeTaskNmae(self, name):
        """输入任务名称"""
        self.driver.type('css=>#taskName', name)

    def getAllmyDataFileid(self):
        """获取所有第一级目的文件夹id"""
        query_list = self.driver.get_attributes('css=>#pathTree>li', 'id')
        return query_list

    def chosemyDataFileid(self, Fid):
        """根据id选择目的文件夹"""
        self.driver.click("css=>#{}_span".format(Fid))

    def typeStartTime(self, stime):
        """输入开始时间"""
        self.driver.clear('css=>#startTime')
        self.driver.type('css=>#startTime', stime)

    def typeEndTime(self, etime):
        """输入结束时间"""
        self.driver.clear('css=>#endTime')
        self.driver.type('css=>#endTime', etime)

    def choseTimeInterval(self, Interval='day', chooseweek='false'):
        """设置个人性化时间，默认每天"""
        if Interval == 'day':
            self.driver.click("css=>input[value='0'][timetype='timeType']")
        if Interval == 'week' and chooseweek == 'false':
            self.driver.click("css=>input[value='1'][timetype='timeType']")
        if Interval == 'week' and chooseweek == 'true':
            self.driver.click("css=>input[value='1'][timetype='timeType']")
            self.driver.click("css=>input[value='MON']")

    def typeExcuteTime(self, excutetime):
        self.driver.clear('css=>#executeTime')
        self.driver.type('css=>#executeTime', excutetime)

    def addOneTask(self, taskname, stime, etime, excutetime, qusery=1, operate=1, SonFile=False, Interval='day', chooseweek='false'):
        """
        添加一条任务
        SonFile，Fasle没有子文件夹，true有子文件夹。需要提前生成下
        """
        self.clickAddTask()
        self.chooseSearchQuery(qusery)
        self.chooseSearchOperate(operate)
        taskfilelist = self.getAllTaskFileid()
        if SonFile:
            js = 'document.getElementsByClassName("route-tree")[0].scrollTop=10000'
            self.driver.js(js)
            time.sleep(1)
            sonfilelist = self.getAllSonTaskFileid(taskfilelist[-1])
            self.clickTaskFileSwitch(taskfilelist[-1])
            self.choseTaskFileByid(sonfilelist)
        else:
            js='document.getElementsByClassName("route-tree")[0].scrollTop=10000'
            self.driver.js(js)
            time.sleep(1)
            self.choseTaskFileByid(taskfilelist[-1])
        self.typeTaskNmae(taskname)
        mydatalist = self.getAllmyDataFileid()
        js = 'document.getElementsByClassName("route-tree")[1].scrollTop=10000'
        self.driver.js(js)
        time.sleep(1)
        self.chosemyDataFileid(mydatalist[-1])
        self.typeStartTime(stime)
        self.typeEndTime(etime)
        self.choseTimeInterval(Interval, chooseweek)
        self.typeExcuteTime(excutetime)
        time.sleep(1)
        self.driver.click("css=>#submit")















